from itsdangerous import BadData
from itsdangerous import TimedJSONWebSignatureSerializer as TJSSerializer
from django.conf import settings


def generate_save_token(openid):
    """对openid进行加密"""

    # 创建序列化器
    serializer = TJSSerializer(settings.SECRET_KEY, 600)
    # 包装加密的数据
    data = {
        'openid': openid
    }
    # dumps进行加密(返回默认是bytes类型)
    access_token_tytes = serializer.dumps(data)

    # 返回

    return access_token_tytes.decode()


def check_save_user_token(access_token):
    """解密"""
    # 创建序列化器
    serializer = TJSSerializer(settings.SECRET_KEY, 600)

    # 反序列化
    try:
        data = serializer.loads(access_token)
    except BadData:
        return None
    else:
        return data.get('openid')